package edu.ustb.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import edu.ustb.domain.Cart;
import edu.ustb.domain.User;
import edu.ustb.mapper.CartMapper;
import edu.ustb.service.CartSearchService;
import edu.ustb.service.CartSearchServiceImpl;

//添加商品到购物车的
@WebServlet("/addCart.action")
@MultipartConfig//servlet3.0支持文件上传
public class CartAddController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
			
		//获取加入购物车的商品的数量
		String itemNum = request.getParameter("addtoCartNum");
		//String itemNum ="10";
		
		//从表单获取goodsId
		String goodsId = request.getParameter("goodsId");
		//int goodsId = 1;
				
		//获取当前用户的id
		User user = (User) request.getSession().getAttribute("user");
		int userId=user.getUserId();
		//int userId=1;
		//获取从表单的提交的商品信息
		Cart addcart = new Cart();
		addcart.setItemGoods(Integer.parseInt(goodsId));
		addcart.setItemNum(Integer.parseInt(itemNum));
		addcart.setItemUser(userId);
		try{
			//读取mybaits核心配置文件，把mybaits.xml以流的形式加载进内存
			InputStream  is = Resources.getResourceAsStream("mybatis.xml");
			SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(is);
			SqlSession openSession = ssf.openSession(true);//事物的自动提交
			CartMapper mapper = openSession.getMapper(CartMapper.class);
	
			//判断该商品是否已经在购物车中
	
			Cart cart=mapper.isGoodsInCart(Integer.parseInt(goodsId));		
			//Cart cart=mapper.isGoodsInCart(1);	

			if (cart==null){
				//如果购物车中没有该商品，就添加该商品和加入购物车的数量到shopitems表						
				int rows = mapper.addCart(addcart);
				if(rows>0){
					request.getRequestDispatcher("/cart.action").forward(request, response);
				}
			}else{
				//如果购物车已经有该商品，就直接修改数量
				cart.setItemNum(Integer.parseInt(itemNum));
				int rows = mapper.updateCart(cart);
				if(rows>0){
					request.getRequestDispatcher("/cart.action").forward(request, response);
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
	}		
}
